// 新建server服务器
var http = require('http')
var url = require('url')

var hostname = '127.0.0.1'
var port = 3000

var server = http.createServer(function (req, res) {
  // 解析请求，包括文件名
  var params = url.parse(req.url, true)
  var pathname = params.pathname
  var query = params.query
  console.log('--------------------------------------')
  console.log('Request for ' + pathname + ' received.')
  console.log('Request for ' + params.path + ' received.')
  console.log('Request for ' + JSON.stringify(query) + ' received.')

  res.statusCode = 200
  // 指定允许其他域名访问
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Content-Type', 'application/json')

  if (pathname === '/login') {
    res.write(login(query))
  } else if (pathname === '/checkSessionId') {
    res.write(checkSessionId(query))
  }
  res.end('')
})

server.listen(port, hostname, function () {
  console.log('Server running at http://%s:%s', hostname, port)
})

function login (query) {
  var account = query.account
  var password = query.password
  console.log('login() for ' + account + ',' + password)
  var result = {
    sessionId: 'sessionId_' + account + '-' + password
  }
  return JSON.stringify(result)
}

function checkSessionId (query) {
  console.log('checkSessionId() for ' + query.sessionId)
  var result = {
    result: 1
  }
  return JSON.stringify(result)
}
